package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.JxwEntity;
import com.jike.noobmoney.mvp.view.fragment.IndexFragment;
import com.jike.noobmoney.mvp.view.fragment.MyFragment;
import com.jike.noobmoney.mvp.view.fragment.MyFragmentUpdate;
import com.jike.noobmoney.mvp.view.fragment.RankFragment;
import com.jike.noobmoney.mvp.view.fragment.TaskAllFragment;
import com.jike.noobmoney.mvp.view.fragment.TaskFragment;
import com.jike.noobmoney.mvp.view.fragment.TaskTwoFragment;
import com.jike.noobmoney.mvp.view.fragment.TuijianFragment;
import com.jike.noobmoney.mvp.view.widget.FragementViewPager;
import com.jike.noobmoney.mvp.view.widget.HongbaoDialog;
import com.jike.noobmoney.mvp.view.widget.MainViewPagerAdapter;
import com.jike.noobmoney.mvp.view.widget.bottombarlayout.BottomBarItem;
import com.jike.noobmoney.mvp.view.widget.bottombarlayout.BottomBarLayout;
import com.jike.noobmoney.net.ApiStore;
import com.jike.noobmoney.rxbus.RxBusRoute;
import com.jike.noobmoney.rxbus.RxEvent;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.lz.aiwan.littlegame.bean.AdConfig;
import com.lz.aiwan.littlegame.utils.LzLittleGame;
import com.lz.playmy.WoWanSdk;
import com.mdad.sdk.mduisdk.AdManager;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.toomee.mengplus.common.TooMeeConstans;
import com.toomee.mengplus.common.utils.EncryptUtils;
import com.toomee.mengplus.common.widget.TooMeeImageLoader;
import com.toomee.mengplus.manager.TooMeeManager;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends BaseActivity {


    @BindView(R.id.vp_content)
    FragementViewPager viewPager;
    @BindView(R.id.tab1_home)
    BottomBarItem tab1Home;
    @BindView(R.id.tab4_task)
    BottomBarItem tab4Task;
    @BindView(R.id.tab2_tuijian)
    BottomBarItem tab2Tuijian;
    @BindView(R.id.tab3_my)
    BottomBarItem tab3My;
    @BindView(R.id.bbl_main)
    BottomBarLayout bblMain;

    private ArrayList<Fragment> fragmentList = new ArrayList<>();
    private int currentIndex = 0;
    private MainViewPagerAdapter adpter;
    private long TOUCH_TIME = 0;
    private static final long WAIT_TIME = 2000L;
    private String userid;
    private String imie;
    private String username;


    @Override
    protected int layoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public Boolean isfits() {
        return true;
    }

    @Override
    public boolean ismain() {
        return true;
    }

    @Override
    protected void initData() {
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        imie = SPUtils.getInstance().getString(ConstantValue.SpType.imie);
        username = SPUtils.getInstance().getString(ConstantValue.SpType.account_username);

        //初始化三方
        initThrid();
        //注册聚享玩的新用户
        getJxwData();
        //初始化tab
        initTab();
        AdManager.getInstance(this).init(this, ConstantValue.appId, userid, ConstantValue.key, "");

        boolean aNew = getIntent().getBooleanExtra("new", false);
        if (aNew) {
            startActivityForResult(new Intent(context, NewTaskActivity.class), 200);
        }

        HongbaoDialog hongbaoDialog = HongbaoDialog.getInstance();
        hongbaoDialog.show(getSupportFragmentManager(), "hongbao");
        hongbaoDialog.setClickCallback(new HongbaoDialog.OnClickCallback() {
            @Override
            public void lianqu() {
                hongbaoDialog.dismiss();
                startActivity(new Intent(context, CheckInActivity.class));
            }
        });
       // initLittle();
    }

    /**
     * 获取聚享玩的用户token
     */
    private void getJxwData() {
        String var1 = "197";
        String var2 = userid;
        String var3 = "4211249485c957e9de4070a36acddc82";
        StringBuilder var6 = new StringBuilder();
        var6.append(var1).append(var2).append(var3);
        String token = EncryptUtils.encryptMD5ToString(var6.toString());
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.juxiangwan.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiStore httpService = retrofit.create(ApiStore.class);
        Map<String, String> queryMap = new HashMap<>();
        queryMap.put("act", "fast_reg_utoken");
        queryMap.put("act_type", "1");
        queryMap.put("mid", var1);
        queryMap.put("resource_id", var2);
        queryMap.put("device_code", imie);
        queryMap.put("from", "h5android");
        queryMap.put("version", "2.0");
        queryMap.put("sign", token);
        Call<JxwEntity> jxw = httpService.getJxw(queryMap);
        jxw.enqueue(new Callback<JxwEntity>() {
            @Override
            public void onResponse(Call<JxwEntity> call, Response<JxwEntity> response) {
                if (response != null) {
                    JxwEntity body = response.body();
                    if (body != null && body.getCode() == 1) {
                        if (body.getData() != null) {
                            String utoken = body.getData().getUtoken();
                            Logger.e("xuke", "utoken=" + utoken);
                            SPUtils.getInstance().put(ConstantValue.SpType.utoken, utoken);
                        } else {
                            SPUtils.getInstance().put(ConstantValue.SpType.utoken, "");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<JxwEntity> call, Throwable t) {

            }
        });
    }

    /**
     * 初始化三方sdb
     */
    private void initThrid() {
        //初始化我玩sdk
        WoWanSdk.init("1214", userid, imie, "9Xi5RGjSa006neHpSoijn7XtZdjZp9Kn");

        //初始化聚享玩sdk
        TooMeeManager.init(this, "197", userid, "4211249485c957e9de4070a36acddc82", new TooMeeImageLoader() {
            @Override
            public void loadImage(String s, ImageView imageView) {
                Glide.with(MainActivity.this).load(s).into(imageView);
            }

            @Override
            public void loadImage(int i, ImageView imageView, int i1) {
                Glide.with(MainActivity.this).load(i).into(imageView);
            }
        });

        TooMeeConstans.IS_OPEN_WEBVIEW_ONPAUSE = false;

        //初始化微信支付
        IWXAPI api = WXAPIFactory.createWXAPI(this, ConstantValue.Wechat_Appid, true);
        api.registerApp(ConstantValue.Wechat_Appid);

        Set<String> tags = new HashSet<String>();
        tags.add("news");

        //设置极光别名
        JPushInterface.setAlias(this, 100, userid);
        JPushInterface.setMobileNumber(this, 200, username);
        JPushInterface.setTags(this, 300, tags);
    }

    private void initTab() {
        //HomeFragment homeFragment = new HomeFragment();
        //fragmentList.add(homeFragment);
       // TaskFragment taskFragment = new TaskFragment();
        IndexFragment indexFragment = new IndexFragment();
        RankFragment rankFragment = new RankFragment();
        TuijianFragment tuijianFragment = new TuijianFragment();
        //TuijianFragmentCopy tuijianFragmentcopy = new TuijianFragmentCopy();
        MyFragmentUpdate myFragment = new MyFragmentUpdate();
        fragmentList.add(indexFragment);
        fragmentList.add(rankFragment);
        fragmentList.add(tuijianFragment);
        //fragmentList.add(tuijianFragmentcopy);
        fragmentList.add(myFragment);


        adpter = new MainViewPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adpter);
        viewPager.setOffscreenPageLimit(fragmentList.size());
        bblMain.setViewPager(viewPager);
        bblMain.setCurrentItem(0);
        bblMain.setOnItemSelectedListener((bottomBarItem, position) -> {
            //选择之后的处理
            currentIndex = position;

        });
    }

    public void goRecommend(int flag) {
        if (bblMain != null) {
            bblMain.setCurrentItem(flag);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
                    finish();
                } else {
                    TOUCH_TIME = System.currentTimeMillis();
                    ToastUtils.showShortToast("再按一次退出");
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected boolean isRegistRxBus() {
        return true;
    }

    /**
     * 注册订阅事件
     */
    protected void receiveEvent(RxEvent rxEvent) {
        switch (rxEvent.busName) {
            case RxBusRoute.LOGIN_OUT:
                //退出登录
                //userid  //nick  //avatar  //recode
                SPUtils.getInstance().remove(ConstantValue.SpType.userid);
                SPUtils.getInstance().remove(ConstantValue.SpType.recode);
                SPUtils.getInstance().remove(ConstantValue.SpType.newavatar);
                startActivity(new Intent(context, LoginActivity.class));
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            goRecommend(2);
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        AdManager.getInstance(this).onAppExit();

        //销毁sdk实例
        LzLittleGame.getInstance().onSdkDestory();
    }
    public void initLittle()
    {
        //1.配置参数
        AdConfig adConfig = new AdConfig();
        adConfig.setTtRewardVideo_h_code("945034015");//穿山甲横屏激励视屏广告位id
        adConfig.setTtRewardVideo_v_code("945034015");//穿山甲竖屏激励视频广告位id     928375517
        adConfig.setTtFullVideo_h_code("945034015");//穿山甲横屏全屏视频广告位id
        adConfig.setTtFullVideo_v_code("945034015");//穿山甲竖屏全屏视频广告位id
        adConfig.setTtNativeCode("945034015");//穿山甲插屏广告位id
        adConfig.setTtSplashCode("945034015");////穿山甲开屏广告位id
        adConfig.setTtLoadingNativeCode("945034015");//打开游戏，加载时候的穿山甲插屏广告id、、
        adConfig.setTtGameEndFeedAdId("945034015");//游戏结束确认退出弹框上的穿山甲信息流广告id

        adConfig.setBooleanhideFnishGameDialog(false);//是否隐藏游戏结束时候确认退出dialog。默认不隐藏

        adConfig.setUserid(userid);//必填

        LzLittleGame.getInstance().LaunchLGSDK(this, "1021", "FyzP3scK6d5Q983RiyzHu5tD2eDBlzJr", adConfig);

        LzLittleGame.getInstance().getAdConfig();
        LzLittleGame.getInstance().getAppkey();
        LzLittleGame.getInstance().getAppid();
    }

}
